package com.fangyi.yunmusic.service.aspect;

import com.alibaba.fastjson.JSON;
import com.fangyi.yunmusic.aspect.ElasticSearchAspect;
import com.fangyi.yunmusic.pojo.vo.PlaylistVO;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
@Aspect
@EnableAspectJAutoProxy(proxyTargetClass = false)
public class PlaylistCacheAspect {

    public static final String PLAYLIST = "playlist";

    private Logger logger = LoggerFactory.getLogger(PlaylistCacheAspect.class);

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @Pointcut("execution(* com.fangyi.yunmusic.service.PlaylistService.getPlaylistVO(..))")
    private void check(){}

    @Around("check()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable{
        // 得到方法参数
        Object[] args = pjp.getArgs();
        String playlistId = (String) args[0];
        String playlistKey = PLAYLIST + ":" + playlistId;
        String value = redisTemplate.opsForValue().get(playlistKey);

        // 缓存里有，直接返回缓存结果
        if (value != null) {
            PlaylistVO playlistVO = (PlaylistVO) JSON.parse(value);
            return playlistVO;
        }

        // 缓存里没有，从数据库读
        PlaylistVO playlistVO = (PlaylistVO) pjp.proceed();
        // 保存到缓存
        redisTemplate.opsForValue().set(playlistKey, JSON.toJSONString(playlistVO));

        // 返回结果
        return playlistVO;
    }

}
